# -*- coding: utf-8 -*-
from flask import Blueprint, g
from common.response import success, error
from common.error_code import ErrorCode
from filter.decorators import validate_request, require_role
from model.request import GetSubjectTeacherRequest, SetHeadTeacherRequest, ListClassesRequest, SetSubjectTeacherRequest
from dao.db import db
from dao.user_dao import Class, Teacher, User
from dao.class_dao import ClassSubjectTeacher
from filter.auth import auth_required

classmgr_bp = Blueprint('classmgr', __name__, url_prefix='/api/classmgr')

@classmgr_bp.route('/set-head-teacher', methods=['POST'])
@auth_required
@require_role(['admin'])  # 仅管理员可调用
@validate_request(SetHeadTeacherRequest)
def set_head_teacher():
    """指定班级班主任接口"""
    data = g.request_data

    # 1. 验证管理员口令
    admin_teacher = Teacher.query.filter_by(user_id=g.user_id).first()
    if not admin_teacher:
        return error(ErrorCode.FORBIDDEN, "当前用户不是教师，无法验证口令")

    if admin_teacher.password_hash != data.admin_password:
        return error(ErrorCode.INVALID_PARAM, "管理员口令错误")

    # 2. 检查班级是否存在
    cls = Class.query.get(data.class_id)
    if not cls:
        return error(ErrorCode.NOT_FOUND, "班级不存在")

    # 3. 检查班级年级是否允许设置班主任
    if cls.grade >= 10:
        return error(ErrorCode.FORBIDDEN, "该班级已毕业，不能设定班主任")

    # 4. 检查老师是否存在
    teacher = Teacher.query.get(data.teacher_id)
    if not teacher:
        return error(ErrorCode.NOT_FOUND, "教师不存在")

    # 5. 更新班主任ID
    cls.head_teacher_id = data.teacher_id
    db.session.commit()

    return success({
        "class_id": cls.id,
        "class_name": cls.name,
        "grade": cls.grade,
        "head_teacher_id": cls.head_teacher_id,
        "head_teacher_name": teacher.user.name
    })

@classmgr_bp.route('/list-classes', methods=['POST'])
@auth_required
@require_role(['admin', 'teacher'])  # admin 或 teacher 可调用
@validate_request(ListClassesRequest)
def list_classes():
    """列出所有负责的班级"""
    data = g.request_data

    # 1. 构建查询条件
    if data.is_graduated == 1:
        # 已毕业
        query = Class.query.filter(Class.grade >= 10)
    else:
        # 在校
        query = Class.query.filter(Class.grade < 10)

    # 2. 根据角色过滤
    if g.role == 'teacher':
        teacher = Teacher.query.filter_by(user_id=g.user_id).first()
        if not teacher:
            return error(ErrorCode.NOT_FOUND, "教师不存在")
    
        # 班主任班级 ID
        head_teacher_ids = db.session.query(Class.id).filter_by(head_teacher_id=teacher.id)

        # 任课老师班级 ID
        subject_teacher_ids = db.session.query(ClassSubjectTeacher.class_id).filter_by(teacher_id=teacher.id)

        # 合并去重（union 自动去重，且空集合不会报错）
        class_ids = head_teacher_ids.union(subject_teacher_ids).subquery()

        # 只保留该老师负责的班级
        query = query.filter(Class.id.in_(class_ids))

    # 3. 执行查询
    classes = query.all()

    # 4. 格式化返回
    result = [
        {
            "id": cls.id,
            "name": cls.name,
            "grade": cls.grade
        }
        for cls in classes
    ]

    return success(result)

@classmgr_bp.route('/set-subject-teacher', methods=['POST'])
@auth_required
@require_role(['admin', 'teacher'])
@validate_request(SetSubjectTeacherRequest)
def set_subject_teacher():
    """设定班级的任课老师"""
    data = g.request_data

    # 1. 验证管理员/教师口令
    current_teacher = Teacher.query.filter_by(user_id=g.user_id).first()
    if not current_teacher:
        return error(ErrorCode.FORBIDDEN, "当前用户不是教师，无法验证口令")

    if current_teacher.password_hash != data.admin_password:
        return error(ErrorCode.INVALID_PARAM, "管理员/教师口令错误")

    # 2. 检查班级是否存在
    cls = Class.query.get(data.class_id)
    if not cls:
        return error(ErrorCode.NOT_FOUND, "班级不存在")

    # 3. 如果是teacher权限，必须是该班级的班主任
    if g.role == 'teacher' and cls.head_teacher_id != current_teacher.id:
        return error(ErrorCode.FORBIDDEN, "你不是该班级的班主任，无权操作")

    # 4. 检查班级是否已毕业
    if cls.grade >= 10:
        return error(ErrorCode.FORBIDDEN, "该班级已毕业，不能更改任课老师")

    # 5. 检查教师是否存在
    teacher = Teacher.query.get(data.teacher_id)
    if not teacher:
        return error(ErrorCode.NOT_FOUND, "教师不存在")
    
    # 获取教师姓名（确保user表关联正常）
    teacher_user = User.query.get(teacher.user_id)
    if not teacher_user:
        return error(ErrorCode.NOT_FOUND, "教师用户信息不存在")

    # 6. 检查class_id, teacher_id, subject的组合是否已存在
    existing_record = ClassSubjectTeacher.query.filter_by(
        class_id=data.class_id,
        teacher_id=data.teacher_id,
        subject=data.subject
    ).first()
    
    # 如果组合已存在，直接返回成功
    if existing_record:
        return success({
            "id": existing_record.id,
            "class_id": data.class_id,
            "subject": data.subject,
            "teacher_id": data.teacher_id,
            "teacher_name": teacher_user.name
        })

    # 7. 处理记录的新增或更新（组合不存在的情况）
    if data.id is not None:
        # 存在id参数，更新对应记录
        update_record = ClassSubjectTeacher.query.get(data.id)
        if not update_record:
            return error(ErrorCode.NOT_FOUND, f"ID为{data.id}的记录不存在")
        
        # 更新记录字段
        update_record.class_id = data.class_id
        update_record.teacher_id = data.teacher_id
        update_record.subject = data.subject
        record_id = data.id
    else:
        # 不存在id参数，新增记录
        new_record = ClassSubjectTeacher(
            class_id=data.class_id,
            subject=data.subject,
            teacher_id=data.teacher_id
        )
        db.session.add(new_record)
        db.session.flush()  # 获取新增记录的ID
        record_id = new_record.id

    db.session.commit()

    return success({
        "id": record_id,
        "class_id": data.class_id,
        "subject": data.subject,
        "teacher_id": data.teacher_id,
        "teacher_name": teacher_user.name,
    })

@classmgr_bp.route('/get-subject-teacher', methods=['POST'])
@auth_required
@require_role(['admin', 'teacher'])
@validate_request(GetSubjectTeacherRequest)
def get_class_teachers():
    """获取班级所有任课老师列表（不包括班主任）"""
    data = g.request_data
    
    # 1. 验证班级是否存在
    cls = Class.query.get(data.class_id)
    if not cls:
        return error(ErrorCode.NOT_FOUND, f"班级ID {data.class_id} 不存在")
    
    # 2. 权限验证（教师只能查看自己负责的班级）
    if g.role == 'teacher':
        current_teacher = Teacher.query.filter_by(user_id=g.user_id).first()
        if not current_teacher:
            return error(ErrorCode.FORBIDDEN, "教师信息不存在")
        
        # 检查是否为该班级的班主任或任课老师
        is_head_teacher = (cls.head_teacher_id == current_teacher.id)
        if not is_head_teacher:
            return error(ErrorCode.FORBIDDEN, "你没有权限查看该班级的任课老师")
    
    # 3. 查询班级所有任课老师（通过class_subject_teacher表）
    teacher_query = db.session.query(
        Teacher.id.label('teacher_id'),
        Teacher.user_id,
        User.name.label('teacher_name'),
        ClassSubjectTeacher.subject,
        ClassSubjectTeacher.id
    ).join(
        ClassSubjectTeacher, Teacher.id == ClassSubjectTeacher.teacher_id
    ).join(
        User, Teacher.user_id == User.id
    ).filter(
        ClassSubjectTeacher.class_id == data.class_id,
    )
    
    teachers = teacher_query.all()
    
    # 4. 格式化返回结果
    result = []
    for teacher in teachers:
        result.append({
            "id": teacher.id,
            "teacher_id": teacher.teacher_id,
            "user_id": teacher.user_id,
            "teacher_name": teacher.teacher_name,
            "subject": teacher.subject
        })
    
    return success(result)